<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="user.mobile"
        name="mobile"
        label="手机号"
        left-icon="phone-o"
        placeholder="请输入11位手机号"
        :rules="[
          {
            required: true,
            message: '请输入正确的手机号',
            trigger: 'onBlur',
            pattern: /^1[3456789]\d{9}$/,
          },
        ]"
      />
      <van-field
        v-model="user.password"
        :type="!isPwdShow?'password':'text'"
        name="code"
        label="密码"
        :left-icon="!isPwdShow?'closed-eye':'eye-o'"
        placeholder="请输入六位数字密码"
        @click-left-icon="isPwdShow=!isPwdShow"
        :rules="[
          {
            required: true,
            message: '请输入正确的密码',
            trigger: 'onBlur',
            pattern: /^\d{6}$/,
          },
        ]"
      />
      <div style="margin: 16px">
        <van-button round block type="info"
         native-type="submit"
         :loading="isLoading"
         :disabled="isLoading"
         loading-text="登录中..."
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { Form, Field, Button, Notify } from 'vant'
import { loginAPI } from '@/api'
import { setToken, setRefreshToken } from '@/utils/token'
export default {
  name: 'Login',
  components: {
    vanForm: Form,
    vanField: Field,
    vanButton: Button
  },
  data () {
    return {
      isPwdShow: false,
      isLoading: false, // 登录加载
      user: {
        mobile: '13811111111', // 手机号
        password: '' // 密码
      }
    }
  },
  methods: {
    async onSubmit (values) {
      // 等待登录成功，此时禁止点击登录按钮
      this.isLoading = true
      try {
        const res = await loginAPI(values)
        console.log(res)
        // 保存token到本地
        setToken(res.data.data.token)
        console.log(res.data.data.token)
        // 续签token
        setRefreshToken(res.data.data.refresh_token)
        // 提示登录成功
        Notify({ type: 'success', message: '登录成功', duration: 1000 })
        // 最后跳转到首页
        console.log(this.$route.query.path)
        this.$router.replace({
          // 跳转到首页,如果有未遂的地址就跳回去
          path: this.$route.query.path || '/layout/home'
        })
      } catch (error) {
        console.log(error.message)
        // 提示登录失败
        Notify({ type: 'danger', message: '账号或密码错误！', duration: 1000 })
      }
      // 登录成功或登录失败把禁用放开
      this.isLoading = false
    }
  }
}
</script>

<style lang='less' scoped>
</style>
